#!/bin/bash
# Job yaml can send below ENVIRONMENT VARIABLES to me
# - mode
# - runtime
# - iterations
# - presync
# END ENVIRONMENT VARIABLES

## Use the /sys/power/state file to control system sleep states.
## And some code from http://people.canonical.com/~apw/suspend-resume/test-suspend

[ -n "$mode" ] || mode='freeze'
[ -n "$runtime" ] || runtime=600
[ -n "$iterations" ] || iterations=10

wakeup_interval=60

trace_dir=/sys/kernel/debug/tracing
event_dir=/sys/kernel/debug/tracing/events/power

tevents=('suspend_resume' 'device_pm_callback_start' 'device_pm_callback_end')

setup_wakeup_timer()
{
	timeout="$1"

	#
	# Request wakeup from the RTC or ACPI alarm timers.  Set the timeout
	# at 'now' + $timeout seconds.
	#
	ctl='/sys/class/rtc/rtc0/wakealarm'
	if [ -f "$ctl" ]; then
		echo "+$timeout" >"$ctl"
		return 0
	fi
	ctl='/proc/acpi/alarm'
	if [ -f "$ctl" ]; then
		date '+%F %T' -d '+ '$timeout' seconds' >"$ctl"
		return 0
	fi

	echo "no method to awaken machine automatically" 1>&2
	exit 1
}

for event in "${tevents[@]}"; do
        echo 1 > $event_dir/$event/enable
done

for i in $(seq $iterations)
do
	setup_wakeup_timer "$wakeup_interval"
	[ "$presync" != "presync" ] || sync
	echo $mode > /sys/power/state
done

for event in "${tevents[@]}"; do
        echo 0 > $event_dir/$event/enable
done

cat $trace_dir/trace

echo "SUSPEND RESUME TEST SUCCESS"
